package com.zgjkhis.modules.util;

import sun.security.provider.SHA;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @Author yxl
 * @Description 加密算法
 * @Date 2021/7/19 13:16
 **/
public class SHAUtils {
    private static final SHA INSTANCE = new SHA();

    private SHAUtils() {
    }

    public static SHA getInstance() {
        return INSTANCE;
    }

    public static String sha1(String str) {
        return sha(str,"SHA1");
    }

    public static String sha512(String str) {
        return sha(str,"SHA-512");
    }

    /**
     * SHA-1 加密
     *
     * @param str
     * @return
     */
    public static String sha(String str,String algorithm) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        try {
            MessageDigest mdTemp = MessageDigest.getInstance(algorithm);
            mdTemp.update(str.getBytes(StandardCharsets.UTF_8));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
